package com.bole.controller;

import com.bole.data.Result;
import com.bole.dto.article.ArticleDTO;
import com.bole.pojo.ArticleDo;
import com.bole.service.ArticleService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("article")
@Api
public class ArticleController {
    @Resource
    private ArticleService articleService;

    @GetMapping
    public Result listArticle() {
        try {
            List<ArticleDo> list = articleService.listArticle();
            return Result.ok().setData(list);
        } catch (Exception e) {
            return Result.fail().setData("资讯查询错误");
        }
    }

    @GetMapping("/id")
    public Result articleById(@PathVariable("id")Long id) {
        try {
            ArticleDo articleDo = articleService.articleById(id);
            ArticleDTO articleDTO = new ArticleDTO();
            BeanUtils.copyProperties(articleDo,articleDTO);
            return Result.ok().setData(articleDTO);
        } catch (Exception e) {
            return Result.fail().setData("资讯查询错误");
        }
    }

    /**
     * 保存
     * @param articleDTO
     * @return
     */
    @PostMapping
    public Result saveArticle(@RequestBody ArticleDTO articleDTO) {
        try {
            ArticleDo articleDo = new ArticleDo();
            BeanUtils.copyProperties(articleDTO,articleDo);
            articleService.saveArticle(articleDo);
            return Result.ok().setData("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail().setData("保存失败");
        }
    }

    /**
     * 修改
     * @param id
     * @param articleDTO
     * @return
     */
    @PostMapping("/{id}")
    public Result updateArticle(@PathVariable("id") Long id,@RequestBody ArticleDTO articleDTO) {
        try {
            articleDTO.setId(id);
            ArticleDo articleDo = new ArticleDo();
            BeanUtils.copyProperties(articleDTO,articleDo);
            articleService.saveArticle(articleDo);
            return Result.ok().setData("修改成功");
        } catch (Exception e) {
            return Result.fail().setData("修改失败");
        }
    }
}
